//
//  LGPatientTableController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/2/23.
//  患者首页 -- 患者列表

#import "LGPatientTableController.h"

//分组管理
#import "LGGroupManageController.h"

//患者详情 - 癌症（圆荷健康）
#import "LGPatientDetailController_YHJK.h"
#import "LGPatientDetailController2.h"

//患者档案 -- 市一（慢阻肺、哮喘）
#import "LGPatientDetailController2.h"

#import "LGPatientHomeHeaderView.h"
//筛选
#import "LGCommonScreenView.h"
#import "LGPatientSectionView.h"
#import "LGPatientHomeCell.h"

#import "LGPatientGroupModel.h"
#import "LGPatientModel.h"

#define viewHeight  (Screen_H-topBarHeight-tabBarHeight-viewPix(7))

#define topHeight   viewPix(50)

@interface LGPatientTableController ()<UITableViewDelegate,UITableViewDataSource,LGPatientHeaderDelegate>
/**   */
@property (nonatomic , strong)LGCommonScreenView *screenView;
/**   */
@property (nonatomic , strong)UITableView *tableView;

/**   */
@property (nonatomic , strong)NSMutableArray *dataArray;
/**   */
@property (nonatomic , strong)NSMutableDictionary *openDic;
/**  筛选条件 */
@property (nonatomic , strong)NSMutableDictionary *screenDic;
/**   */
@property (nonatomic , strong)LGPatientHomeHeaderView *headerView;
/**   */
@property (nonatomic , copy)NSString *pageNo;
@end

@implementation LGPatientTableController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gradientLayer.hidden = YES;
    self.view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    [self emptyViewWithSuperView:self.tableView frame:CGRectMake(0, kMaxY(self.headerView.frame), Screen_W, Screen_H-topHeight-tabBarHeight-self.headerView.bounds.size.height)];
    self.emptyView.backgroundColor = [UIColor clearColor];
    [[UIApplication sharedApplication].keyWindow addSubview:self.screenView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestScreenData) name:@"refreshPatientTable" object:nil];
    [self requestScreenData];
}


//请求筛选数据
-(void)requestScreenData{
    [RequestUtil withPOST:self.filterAction parameters:@{@"is_team":self.is_team} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.screenView.itemArray = returnData;
            [self sureScreenAction];
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)requestData{
    self.pageNo = @"1";
    [self requestMoreData];
}

-(void)requestMoreData{
    NSMutableDictionary *parama = [NSMutableDictionary dictionary];
    [parama setValue:[ObjectTool objectToJson:self.screenDic] forKey:@"filter"];
    [parama setValue:self.is_team forKey:@"is_team"];
    [parama setValue:self.pageNo forKey:@"pageNo"];
    [parama setValue:@"20" forKey:@"pageSize"];
    [RequestUtil withPOST:self.searchAction parameters:parama withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if([self.pageNo isEqualToString:@"1"]){
            self.dataArray = [NSMutableArray array];
        }
        if(code == 200){
            self.headerView.totalCount = LGNSString(returnData[@"total"]);
            NSArray *tempArray = returnData[@"data"];
            if(tempArray.count>0){
                self.pageNo = [NSString stringWithFormat:@"%ld",[returnData[@"current_page"] integerValue]+1];
                [self.dataArray addObjectsFromArray:tempArray];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [self.tableView reloadData];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无符合条件的患者" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无符合条件的患者" offset:0];
        }
    }];
}

//分组管理
-(void)groupManageAction{
    LGGroupManageController *controller = [[LGGroupManageController alloc]init];
    [self.navigationController pushViewController:controller animated:YES];
}

//筛选
-(void)screenBtnAction{
    [self.screenView showScreenViewAnimation];
}

//重置筛选
-(void)resetScreenAction{
    self.screenDic = [NSMutableDictionary dictionary];
    [self.screenView resetDataAction];
    [self.screenView closeViewAction];
    self.headerView.dataDic = @{};
    [self requestData];
}

//删除筛查选项
-(void)deleteScreenItem:(NSDictionary *)itemDic{
    NSString *key = LGNSString(itemDic[@"key"]);
    NSString *content = LGNSString(itemDic[@"title"]);
    if([self.screenView.screenDic.allKeys containsObject:key]){
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:self.screenView.screenDic[key]];
        if([tempDic.allKeys containsObject:content]){
            [tempDic removeObjectForKey:content];
        }
        [self.screenView.screenDic setValue:tempDic forKey:key];
    }
    [self.screenView.collectionView reloadData];
    [self sureScreenAction];
}

//确定筛选
-(void)sureScreenAction{
    self.screenDic = [NSMutableDictionary dictionary];
    NSArray *keyArray = self.screenView.screenDic.allKeys;
    for (NSInteger i=0; i<keyArray.count; i++) {
        NSDictionary *tempDic = self.screenView.screenDic[keyArray[i]];
        NSArray *titleArray = tempDic.allKeys;
        if(titleArray.count>0){
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSInteger j=0; j<titleArray.count; j++) {
                [tempArray addObject:@{@"title":titleArray[j],@"ids":tempDic[titleArray[j]]}];
            }
            [self.screenDic setValue:tempArray forKey:keyArray[i]];
        }
    }
    self.headerView.dataDic = self.screenView.screenDic;
    [self.screenView closeViewAction];
    [self requestData];
}

//headView高度变化
-(void)headViewHeightChanged:(CGFloat)height{
    self.headerView.frame = CGRectMake(0, 0, Screen_W, height);
    self.tableView.tableHeaderView = self.headerView;
    self.emptyView.frame = CGRectMake(0, height, Screen_W, self.tableView.bounds.size.height-height);
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGPatientHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = self.dataArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *tempDic = self.dataArray[indexPath.row];
//    NSString *diseaseCode = LGNSString(tempDic[@"disease_code"]);
    NSString *nodePage = LGNSString(tempDic[@"nodepage"]);
    if ([nodePage isEqualToString:@"1"]) {
        //市一慢阻肺
        LGPatientDetailController2 *controller = [[LGPatientDetailController2 alloc]init];
        controller.patientid = LGNSString(self.dataArray[indexPath.row][@"patient_id"]);
        controller.levelid = LGNSString(self.dataArray[indexPath.row][@"level_id"]);
        controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
        [self.navigationController pushViewController:controller animated:YES];
    }else{
        //其他
        LGPatientDetailController_YHJK *controller = [[LGPatientDetailController_YHJK alloc]init];
        controller.patientid = LGNSString(self.dataArray[indexPath.row][@"patient_id"]);
        controller.levelid = LGNSString(self.dataArray[indexPath.row][@"level_id"]);
        controller.diseaseCode = LGNSString(tempDic[@"disease_code"]);
        [self.navigationController pushViewController:controller animated:YES];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return viewPix(0.01);
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(0.01))];
    return footView;
}


-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, 0, Screen_W, viewHeight);
    self.emptyView.frame = CGRectMake(0, kMaxY(self.headerView.frame), Screen_W, Screen_H-topHeight-tabBarHeight-self.headerView.bounds.size.height);
}



-(NSMutableDictionary *)screenDic{
    if(!_screenDic){
        _screenDic = [NSMutableDictionary dictionary];
    }
    return _screenDic;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewHeight) style:UITableViewStylePlain];
        [_tableView registerClass:[LGPatientHomeCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = self.headerView;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestScreenData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
    }
    return _tableView;
}

-(LGPatientHomeHeaderView *)headerView{
    if(!_headerView){
        _headerView = [[LGPatientHomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(44))];
        _headerView.delegate = self;
        [_headerView.groupBtn addTarget:self action:@selector(groupManageAction) forControlEvents:UIControlEventTouchUpInside];
        [_headerView.screenBtn addTarget:self action:@selector(screenBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _headerView;
}

-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(LGCommonScreenView *)screenView{
    if(!_screenView){
        _screenView = [[LGCommonScreenView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
        [_screenView.resetBtn addTarget:self action:@selector(resetScreenAction) forControlEvents:UIControlEventTouchUpInside];
        [_screenView.sureBtn addTarget:self action:@selector(sureScreenAction) forControlEvents:UIControlEventTouchUpInside];
        _screenView.hidden = YES;
    }
    return _screenView;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)resetOpenSection {
}

@end
